<template>
  <el-dialog
    :title="showTitle"
    :visible="showDialog"
    width="30%"
    @close="close"
  >
    <el-form
      ref="form"
      label-width="100px"
      label-position="left"
      :model="form"
      :rules="rules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入部门编码" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" @focus="focusFn">
          <el-option
            v-for="item in employeeList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          resize="none"
          placeholder="部门介绍"
          type="textarea"
          rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="addFn">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { addDepartment, getDepartmentList, getDepartmentDetail, updateDepartment } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  name: 'AddDept',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    nodeData: {
      type: Object,
      required: true
    }
  },
  data() {
    const checkName = async(rule, value, callback) => {
      // 思路：
      // 1. 发送请求，获取到最新所有的部门信息

      const { depts } = await getDepartmentList()
      let result
      if (this.form.id) {
        // 修改
        // 1. 如果部门名称没有发生改变，是允许的
        if (value === this.nodeData.name) return callback()
        // 2. 如果部门名称发生了改变，需要判断value和兄弟部门的名称是否一致
        result = depts.filter(item => item.pid === this.nodeData.pid)
      } else {
        // 2. 根据nodeData找到它的所有的子部门
        result = depts.filter(item => item.pid === this.nodeData.id)
        // console.log(this.nodeData.id)
        // 3. 判断value和这些子部门的名称是否是重复的
      }
      const has = result.some(item => item.name === value)
      has ? callback(new Error(`${value}已经存在了`)) : callback()
    }
    const checkCode = async(rule, value, callback) => {
      if (this.form.id) {
        // 这是修改功能,允许编码和原来的一致
        if (value === this.nodeData.code) {
          return callback()
        }
      }
      // 这是添加功能
      // 1. 发送请求-获取到最新的部门信息
      const { depts } = await getDepartmentList()
      // 2. 判断value是否和其他部门的code重复
      const has = depts.some(item => item.code === value)
      has ? callback(new Error(`${value}已经存在了`)) : callback()
    }

    return {
      // 收集表单数据
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 提供校验规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空' },
          { max: 50, message: '部门名称长度为1-50' },
          // 自定义校验，校验部门是否重复
          { validator: checkName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空' },
          { max: 50, message: '部门编码长度为1-50' },
          { validator: checkCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空' },
          { max: 300, message: '部门介绍长度为1-300' }
        ]
      },
      // 存放员工列表
      employeeList: []
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑部门' : '新增子部门'
    }
  },
  // created() {
  //   this.getInfo()
  // },
  methods: {
    close() {
      // this.$emit('close')
      this.$emit('update:showDialog', false)
      // 重置表单的校验结果
      // 只会把表单绑定的值给重置，没绑定的就不会重置
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    async focusFn() {
      const data = await getEmployeeSimple()
      console.log(data)
      this.employeeList = data
    },
    async addFn() {
      // 1. 对整体的表单进行校验
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      // 2. 发送请求
      if (this.form.id) {
        await updateDepartment(this.form)
      } else {
        // 新增
        await addDepartment({
          ...this.form,
          pid: this.nodeData.id
        })
      }
      // 3. 提示消息  关闭弹窗  刷新部门
      this.$message.success('操作成功')
      this.$emit('update:showDialog', false)
      this.$emit('getDepartments')
    },
    async getInfo(id) {
      const data = await getDepartmentDetail(id)
      this.form = data
    }
  }
}
</script>

<style>

</style>
